#include<iostream>
#include<memory>


class Base
{
    public:
    Base(){std::cout << "Base constructor." << std::endl;};
    ~Base(){std::cout << "Base destructor." << std::endl;};

    std::shared_ptr<Base> getPtr(){return std::shared_ptr<Base>(this);};//这种做法会被析构两次
};


//奇异递归模式
class TrueBase:public std::enable_shared_from_this<TrueBase>//继承模板类，实例自己
{
    public:
    TrueBase(){std::cout << "Base constructor." << std::endl;};
    ~TrueBase(){std::cout << "Base destructor." << std::endl;};

    std::shared_ptr<TrueBase> getPtr(){return shared_from_this();};//正确做法
};

int main(int argc, char const *argv[])
{
    std::shared_ptr<TrueBase>b (new TrueBase());
    std::cout << "use_count" <<b.use_count() <<std::endl;
    std::shared_ptr<TrueBase>bc = b->getPtr();
    std::cout << "use_count" <<b.use_count() <<std::endl;
    return 0;
}
